<template>
  <div class="admin-orders">
    <header class="header">
      <div class="container">
        <div class="logo">
          <h1>小米商城 - 订单管理</h1>
        </div>
        <nav class="nav">
          <router-link to="/">返回首页</router-link>
          <router-link to="/admin/products">商品管理</router-link>
          <router-link to="/admin/users">用户管理</router-link>
          <router-link to="/admin/orders">订单管理</router-link>
          <router-link to="/admin/categories">分类管理</router-link>
        </nav>
      </div>
    </header>

    <div class="container">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>订单管理</span>
            <el-button type="primary" @click="handleAdd">添加订单</el-button>
          </div>
        </template>

        <el-table :data="orders" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户" />
          <el-table-column prop="product_name" label="商品" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="total_price" label="总价" width="120">
            <template #default="scope">
              ¥{{ scope.row.total_price }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
      >
        <el-form :model="form" label-width="80px">
          <el-form-item label="用户ID">
            <el-input-number v-model="form.user_id" :min="1" />
          </el-form-item>
          <el-form-item label="商品ID">
            <el-input-number v-model="form.product_id" :min="1" />
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number v-model="form.quantity" :min="1" />
          </el-form-item>
          <el-form-item label="总价">
            <el-input-number v-model="form.total_price" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.status">
              <el-option label="待处理" value="pending" />
              <el-option label="已支付" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'

const orders = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加订单')
const form = ref({
  id: null,
  user_id: 1,
  product_id: 1,
  quantity: 1,
  total_price: 0,
  status: 'pending'
})

const getStatusText = (status) => {
  const map = {
    pending: '待处理',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    paid: 'info',
    shipped: '',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

const loadOrders = async () => {
  try {
    const res = await request.get('/orders')
    orders.value = res.data || []
  } catch (error) {
    ElMessage.error('加载订单失败')
  }
}

const handleAdd = () => {
  dialogTitle.value = '添加订单'
  form.value = {
    id: null,
    user_id: 1,
    product_id: 1,
    quantity: 1,
    total_price: 0,
    status: 'pending'
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑订单'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (form.value.id) {
      await request.put(`/orders/${form.value.id}`, form.value)
      ElMessage.success('更新成功')
    } else {
      await request.post('/orders', form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadOrders()
  } catch (error) {
    ElMessage.error(form.value.id ? '更新失败' : '添加失败')
  }
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/orders/${id}`)
    ElMessage.success('删除成功')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 15px 0;
  margin-bottom: 20px;
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo h1 {
  color: #E02E24;
  font-size: 20px;
}

.nav {
  display: flex;
  gap: 20px;
}

.nav a {
  text-decoration: none;
  color: #333;
}

.nav a.router-link-active {
  color: #E02E24;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

